<?php

/**
 * @Author: chenjianghui
 * @Date:   2018-08-07 15:09:57
 * @Last Modified by:   chenjianghui
 * @Last Modified time: 2018-08-09 13:42:25
 */
namespace app\app\controller;

use app\common\model\User;
use app\common\model\UserBindOauth;
use app\common\model\VerifyCode;
use app\common\third\QqModel;
use app\common\third\WechatModel;
use app\common\third\WeiboModel;
use think\Db;

class ThirdLogin extends Common
{
    /**
     * 第三方绑定
     * @Author   chenjianghui
     * @DateTime 2018-07-04T10:14:38+0800
     * @return   [type]                   [description]
     */
    public function oauthUserLogin()
    {
        $data         = request()->post();
        $check_key    = ['access_token', 'openid'];
        $access_token = $data['access_token'];
        $openid       = $data['openid'];
        switch ($data['type']) {
            case 'weixin':
                $oauth_info = WechatModel::getUserInfo($access_token, $openid);
                $source     = 'wechat';
                if ($oauth_info) {
                    $oauth_info['oauth_sn'] = $oauth_info['unionid'] ?: $oauth_info['openid'];
                    $oauth_info['nickname'] = $oauth_info['nickname'];
                    $oauth_info['come']     = request()->header()['device-os'] . request()->header()['os-ver'];
                    $oauth_info['avatar']   = $oauth_info['headimgurl'];
                    $bind_result            = UserBindOauth::getBindUser($oauth_info, $source);
                }
                break;
            case 'qq':
                $headers = request()->header();
                if ($headers['device-os'] == 'iOS') {
                    $oauth_info = QqModel::getUserInfo($access_token, $openid, config('third.ios_qq_appid'));
                }
                if ($headers['device-os'] == 'android') {
                    $oauth_info = QqModel::getUserInfo($access_token, $openid, config('third.android_qq_appid'));
                }
                $source = 'qq';
                if ($oauth_info['ret'] == '-22') {
                    renderJson('授权失败', 0);
                }
                if ($oauth_info) {
                    $oauth_info['oauth_sn'] = $openid;
                    $oauth_info['openid']   = $openid;
                    $oauth_info['sex']      = $oauth_info['gender'] == '男' ? 1 : ($oauth_info['gender'] == '女' ? 2 : 1);
                    $oauth_info['come']     = request()->header()['device-os'] . request()->header()['os-ver'];
                    $oauth_info['avatar']   = $oauth_info['figureurl_qq_2'] ?: $oauth_info['figureurl_qq_1'];
                    $bind_result            = UserBindOauth::getBindUser($oauth_info, $source);
                }
                break;
            case 'weibo':
                $oauth_info = WeiboModel::getUserInfo($access_token, $openid);
                $source     = 'weibo';
                if ($oauth_info) {
                    $oauth_info['oauth_sn'] = $openid;
                    $oauth_info['openid']   = $openid;
                    $oauth_info['nickname'] = $oauth_info['name'] ?: $oauth_info['screen_name'];
                    $oauth_info['sex']      = $oauth_info['gender'] == 'm' ? 1 : 2;
                    $oauth_info['come']     = request()->header()['device-os'] . request()->header()['os-ver'];
                    $oauth_info['avatar']   = $oauth_info['profile_image_url'] ?: '';
                    $bind_result            = UserBindOauth::getBindUser($oauth_info, $source);
                }
                break;
            default:
                renderJson('请正确填写授权类型', 0);
                break;
        }
        if ($bind_result && $bind_result['userObj']) {
            $userObj = $bind_result['userObj'];
            $token   = $userObj->loginFast();
            renderJson('登录成功', 1,
                [
                    'access_token'  => $token,
                    'user_id'       => $userObj->uid,
                    'bind_oauth_id' => 0,
                ]);
        }
        if ($bind_result && $bind_result['bind_oauth_id']) {
            renderJson('请先绑定账号', 1, [
                'access_token'  => '',
                'user_id'       => 0,
                'bind_oauth_id' => $bind_result['bind_oauth_id'],
            ]);
        }
    }

    /**
     * 绑定现有账号
     * @Author   chenjianghui
     * @DateTime 2018-07-12T18:53:38+0800
     * @return   [type]                   [description]
     */
    public function bindAccount()
    {
        $data = request()->post();
        $rule = [
            'bind_number|绑定账号'   => 'require',
            'code|验证码'           => 'require',
            'bind_oauth_id|绑定id' => 'require',
        ];
        $validator = new \think\Validate($rule);
        $result    = $validator->check($data);
        if (!$result) {
            renderJson($validator->getError(), 0);
        }
        // 验证码校验
        $code_obj = VerifyCode::checkCode('bind_mobile', $data['bind_number'], $data['code']);
        $user     = User::where('mobile', $data['bind_number'])->find();
        $bind     = UserBindOauth::get($data['bind_oauth_id']);
        if ($bind) {
            if ($bind->source == 'qq') {
                if ($user->qq) {
                    renderJson('该账号已经绑定qq', 0);
                }
                $arr['qq'] = $bind['nickname'];
            }
            if ($bind->source == 'wechat') {
                if ($user->weixin) {
                    renderJson('该账号已经绑定微信', 0);
                }
                $arr['weixin'] = $bind['nickname'];
            }
            if ($bind->source == 'weibo') {
                if ($user->weibo) {
                    renderJson('该账号已经绑定微博', 0);
                }
                $arr['weibo'] = $bind['nickname'];
            }
            $arr['avatar']   = $user['avatar'] ?: $bind['avatar'];
            $arr['username'] = $user['username'] ?: $bind['nickname'];
            Db::startTrans();
            $res = $user->save($arr);
            $r   = $bind->save(['bind_mobile' => $data['bind_number'], 'user_id' => $user->uid, 'on_time' => time()]);
            if ($res && $r) {
                Db::commit();
                $access_token = $user->loginByMobile();
                if ($access_token) {
                    $code_obj->toSuccess(array('uid' => $user->uid)); // 验证码状态修改
                    renderJson('登录成功', 1, array(
                        'access_token' => $access_token,
                        'user_id'      => $user->uid,
                    ));
                }
            } else {
                Db::rollback();
                renderJson('绑定失败', 0);
            }
        } else {
            renderJson('绑定失败', 0);
        }
    }

    /**
     * 绑定新帐号
     * @Author   chenjianghui
     * @DateTime 2018-08-09T09:28:35+0800
     * @return   [type]                   [description]
     */
    public function bindNewAccount()
    {
        $data = request()->post();
        $rule = [
            'bind_number'    => 'require',
            'code'           => 'require',
            'bind_oauth_id'  => 'require',
            'password'       => 'require|min:6|max:12|/^[0-9a-zA-Z_]{1,}$/',
            'password_again' => 'require',
            'sort_id'        => 'require'
        ];
        $msg = [
            'bind_number.require'    => '请输入手机号码',
            'bind_number'            => '您输入的手机号码格式不正确，请重新输入',
            'code.require'           => '请输入短信验证码',
            'password.require'       => '请输入密码',
            'password.min'           => '密码长度为6-12字符',
            'password.max'           => '密码长度为6-12字符',
            'password'               => '密码不可包含非法字符',
            'password_again.require' => '请输入重复密码',
            'sort_id.require'        => '请选择您的工种'
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) {
            renderJson($validate->getError(), 0);
        }
        if ($data['password'] != $data['password_again']) {
            renderJson('两个输入密码不一致，请重新设置', 0);
        }
        // 用户唯一性判断
        $user = User::where('mobile', $data['bind_number'])->find();
        if ($user) {
            renderJson('该手机号码已被注册', 0);
        }
        // 工种校验
        $work_sort_info = model('WorkSort')->where('sort_id', $data['sort_id'])->find();
        if (!$work_sort_info){
            renderJson('您的工种选择有误', 0);
        }
        // 验证码校验
        $code_obj = VerifyCode::checkCode('bind_mobile', $data['bind_number'], $data['code']);
        $bind     = UserBindOauth::get($data['bind_oauth_id']);

        if ($bind) {
            if ($bind->source == 'qq') {
                if ($user->qq) {
                    renderJson('该账号已经绑定qq', 0);
                }
                $data['qq'] = $bind['nickname'];
            }
            if ($bind->source == 'wechat') {
                if ($user->weixin) {
                    renderJson('该账号已经绑定微信', 0);
                }
                $data['weixin'] = $bind['nickname'];
            }
            if ($bind->source == 'weibo') {
                if ($user->weibo) {
                    renderJson('该账号已经绑定微博', 0);
                }
                $data['weibo'] = $bind['nickname'];
            }

            $data['avatar']   = $bind['avatar'] ?: $user['avatar'];
            $data['username'] = $bind['nickname'] ?: $data['bind_number'];
            $data['mobile']   = $data['bind_number'];
            // 新建user数据
            Db::startTrans();
            $user_obj = new User($data);
            $uid      = $user_obj->smsRegister();
            $r        = $bind->save(['bind_mobile' => $data['mobile'], 'user_id' => $uid, 'on_time' => time()]);
            if ($uid && $r) {
                Db::commit();
                $code_obj->toSuccess(array('uid' => $uid));
                // 注册完直接登录
                $access_token = \app\common\lib\User::encode_token(array('uid' => $uid));
                User::where('uid', $uid)->update(['access_token' => $access_token, 'last_login_time' => time(), 'last_login_ip' => request()->ip()]);
                renderJson('绑定成功', 1, array(
                    'access_token' => $access_token,
                    'user_id'      => $uid,
                ));
            } else {
                Db::rollback();
                renderJson('绑定失败', 0);
            }
        }
    }
}
